package me.numark;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.Bind;
import me.numark.activities.BaseActivity;
import me.numark.activities.MarkActivity;
import me.numark.activities.WebviewActivity;
import me.numark.fragments.AskLoginFragment;
import me.numark.fragments.AskToWebViewFragment;
import me.numark.fragments.DiscoverFragment;
import me.numark.fragments.FeedFragment;
import me.numark.fragments.NoticeFragment;
import me.numark.fragments.ProfileFragment;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Settings;


public class MainActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Bind(R.id.notice_point)
    ImageView noticePoint;

    @Bind(R.id.tab_feed)
    TextView tab_feed;

    @Bind(R.id.tab_discover)
    TextView tab_discover;

    @Bind(R.id.tab_recommend)
    ImageView tab_recommend;

    @Bind(R.id.tab_notice)
    RelativeLayout tab_notice;

    @Bind(R.id.tab_notice_image)
    TextView tab_notice_txt;

    @Bind(R.id.tab_profile)
    TextView tab_profile;

    @Bind(R.id.toast_url)
    TextView toastUrl;

    private int currentFragmentIndex;
    private SparseArray<Fragment> fragments = new SparseArray<Fragment>(4);
    private View[] tabButtons = new View[4];
    private boolean firstVisiable = true;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_main;
        super.onCreate(savedInstanceState);
        Global.appInit(this);
        uiInit();

        if (Global.isLoggedIn())
            switchFragment(0, true);
        else
            switchFragment(1, true);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (Global.isLoggedIn()){
            String text = null;
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            if (clipboard.hasPrimaryClip() && clipboard.getPrimaryClip().getItemCount() > 0) {
                ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
                if (item.getText() != null) {
                    text = item.getText().toString();
                }
            }

            if (text != null && text.trim().startsWith("http")) {
                if (!text.equals(Settings.getUrl())) {
                    toastUrl.setText("发现你复制了链接:"+text+" ,快去推荐吧~");
                    url = text;
                    doToastUrl();
                    Settings.setUrl(text);
                }
            }
        }
    }


    void uiInit() {
        tab_discover.setOnClickListener(this);
        tab_feed.setOnClickListener(this);
        tab_notice.setOnClickListener(this);
        tab_profile.setOnClickListener(this);
        tab_recommend.setOnClickListener(this);
        tabButtons[0] = tab_feed;
        tabButtons[1] = tab_discover;
        tabButtons[2] = tab_notice;
        tabButtons[3] = tab_profile;
        toastUrl.setOnClickListener(this);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
                new IntentFilter(Constants.ACTION_USER_CHANGED));
        LocalBroadcastManager.getInstance(this).registerReceiver(rReceiver,
                new IntentFilter(Constants.ACTION_HAS_UNREAD));
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //outState.putInt("index",currentFragmentIndex);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      /*  currentFragmentIndex = savedInstanceState.getInt("index");
        switchFragment(currentFragmentIndex,true);
        super.onRestoreInstanceState(savedInstanceState);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        for (int i = 0; i < 4; i++) {
            Fragment fragment = fm.findFragmentByTag(String.valueOf(i));
            if (i != currentFragmentIndex && fragment != null) {
                ft.hide(fragment);
            }
        }
        ft.commitAllowingStateLoss();*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(rReceiver);
    }

    /**
     * if (firstVisiable) {
     if (text != null && text.trim().startsWith("http")) {
     if (!text.equals(Settings.getUrl())) {
     AskToWebViewFragment.show(this, text);
     Settings.setUrl(text);
     }
     }
     } else {
     * @param v
     */

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tab_discover) {
            switchFragment(1, false);
            tab_feed.setTextColor(Color.parseColor("#999999"));
            tab_discover.setTextColor(Color.parseColor("#00b16a"));
            tab_notice_txt.setTextColor(Color.parseColor("#999999"));
            tab_profile.setTextColor(Color.parseColor("#999999"));
            return;
        }
        if (!Global.isLoggedIn()) {
            AskLoginFragment.show(this);
            return;
        }
        switch (v.getId()) {
            case R.id.toast_url:
                Intent i = new Intent(this, WebviewActivity.class);
                i.putExtra(WebviewActivity.EXTRA_URL,url);
                i.putExtra(WebviewActivity.FROM_MAIN, true);
                startActivity(i);
                break;
            case R.id.tab_feed:
                switchFragment(0, false);
                tab_feed.setTextColor(Color.parseColor("#00b16a"));
                tab_discover.setTextColor(Color.parseColor("#999999"));
                tab_notice_txt.setTextColor(Color.parseColor("#999999"));
                tab_profile.setTextColor(Color.parseColor("#999999"));
                break;
            case R.id.tab_notice:
                tab_feed.setTextColor(Color.parseColor("#999999"));
                tab_discover.setTextColor(Color.parseColor("#999999"));
                tab_notice_txt.setTextColor(Color.parseColor("#00b16a"));
                tab_profile.setTextColor(Color.parseColor("#999999"));
                noticePoint.setVisibility(View.INVISIBLE);
                //TODO 点击通知 所有消息置为已读 noticePoint不可见
                new RequestServerTask<BaseResponse>(BaseResponse.class) {
                    @Override
                    protected String requestServer() {
                        return HttpUtil.get(String.format(NetworkConstants.MESSAGE_READ_ALL,Global.getCurrentUid()), null);
                    }
                    @Override
                    protected void onSuccess(BaseResponse result) {
                        noticePoint.setVisibility(View.INVISIBLE);
                    }
                }.start();
                switchFragment(2, false);
                break;
            case R.id.tab_profile:
                tab_feed.setTextColor(Color.parseColor("#999999"));
                tab_discover.setTextColor(Color.parseColor("#999999"));
                tab_notice_txt.setTextColor(Color.parseColor("#999999"));
                tab_profile.setTextColor(Color.parseColor("#00b16a"));
                switchFragment(3, false);
                break;
            case R.id.tab_recommend:
                ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                if (clipboard.hasPrimaryClip() && clipboard.getPrimaryClip().getItemCount() > 0) {
                    ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
                    if (item.getText() != null) {
                        String text = item.getText().toString();
                        if (text != null && text.trim().startsWith("http")) {
                            AskToWebViewFragment.show(this,0);
                        }else {
                            AskToWebViewFragment.dismissDelay(AskToWebViewFragment.show(this, 1));
                        }
                    }else{
                        AskToWebViewFragment.dismissDelay(AskToWebViewFragment.show(this, 1));
                    }
                }else {
                    AskToWebViewFragment.dismissDelay(AskToWebViewFragment.show(this, 1));
                }
                break;
        }
    }
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(android.os.Message msg)
        {
            switch (msg.what) {

                case 97:
                    toastUrl.setVisibility(View.GONE);
                    break;
            }
        }
    };

    private void doToastUrl(){
        toastUrl.setVisibility(View.VISIBLE);
        Animator animator = AnimatorInflater.loadAnimator(this, R.animator.update_msg_anim);
        animator.setTarget(toastUrl);
        animator.start();
        mHandler.sendEmptyMessageDelayed(97, 8000);
    }


    private void switchFragment(int id, boolean force) {
        if (currentFragmentIndex == id && !force) {
            return;
        }
        tabButtons[currentFragmentIndex].setSelected(false);
        Fragment oldFragment = fragments.get(currentFragmentIndex);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (oldFragment != null)
            ft.hide(oldFragment);

        currentFragmentIndex = id;
        tabButtons[currentFragmentIndex].setSelected(true);
        Fragment newFragment = fragments.get(currentFragmentIndex);
        if (newFragment == null) {
            switch (currentFragmentIndex) {
                case 0:
                    newFragment = FeedFragment.newInstance(Constants.FEEDTYPE_TIMELINE, Global.getCurrentUid());
                    tab_feed.setTextColor(Color.parseColor("#00b16a"));
                    tab_discover.setTextColor(Color.parseColor("#999999"));
                    tab_notice_txt.setTextColor(Color.parseColor("#999999"));
                    tab_profile.setTextColor(Color.parseColor("#999999"));
                    break;
                case 1:
                    newFragment = new DiscoverFragment();
                    tab_feed.setTextColor(Color.parseColor("#999999"));
                    tab_discover.setTextColor(Color.parseColor("#00b16a"));
                    tab_notice_txt.setTextColor(Color.parseColor("#999999"));
                    tab_profile.setTextColor(Color.parseColor("#999999"));
                    break;
                case 2:
                    newFragment = new NoticeFragment();
                    tab_feed.setTextColor(Color.parseColor("#999999"));
                    tab_discover.setTextColor(Color.parseColor("#999999"));
                    tab_notice_txt.setTextColor(Color.parseColor("#00b16a"));
                    tab_profile.setTextColor(Color.parseColor("#999999"));
                    break;
                case 3:
                    newFragment = new ProfileFragment();
                    tab_feed.setTextColor(Color.parseColor("#999999"));
                    tab_discover.setTextColor(Color.parseColor("#999999"));
                    tab_notice_txt.setTextColor(Color.parseColor("#999999"));
                    tab_profile.setTextColor(Color.parseColor("#00b16a"));
                    break;
            }
            fragments.put(currentFragmentIndex, newFragment);
        }
        if (newFragment != null && id == 3 && userChange == true){
            userChange = false;
            newFragment = new ProfileFragment();
            fragments.put(currentFragmentIndex, newFragment);
        }
        if (newFragment != null) {
            if (!newFragment.isAdded()) {
                ft.add(R.id.fragments, newFragment, String.valueOf(currentFragmentIndex));
            }
            ft.show(newFragment);
        }
        ft.commitAllowingStateLoss();
    }


    boolean userChange = false;
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_USER_CHANGED.equals(intent.getAction())) {
                if (!Global.isLoggedIn()) {
                    switchFragment(1, true);
                }
                if (Global.isLoggedIn()){
                    //switchFragment(1, true);
                    fragments = new SparseArray<>(4);
                    userChange = true;
                    switchFragment(0, true);

                }
            }
        }
    };

    BroadcastReceiver rReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_HAS_UNREAD.equals(intent.getAction())){
                noticePoint.setVisibility(View.VISIBLE);
            }
        }
    };

}
